<template>
  <div class="contract-payment">
    <a-card title="退款管理">
      <div slot="extra">
        <a-button type="primary" @click="addModal">申请退款</a-button>
      </div>
      <a-table
        bordered
        size="middle"
        :row-key="(record) => record.refund_id"
        :columns="refundColumns"
        :data-source="refundData"
      >
        <template slot="amount" slot-scope="text">
          <a-tag color="red">{{ text }}</a-tag>
        </template>
        <template slot="apply_file_url_map" slot-scope="text, record">
          {{ record.apply_file_name }} <a-icon :style="{ color: '#40a9ff', fontSize: '18px' }" type="download" @click="downFile(refund.apply_file_url, refund.apply_file_name)" />
        </template>
        <template slot="communicate_img" slot-scope="text">
          <a :href="text" target="_blank">
            <img :src="text" width="40">
          </a>
        </template>
        <template slot="status" slot-scope="text">
          {{ accountOptions[text] }}
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="editModal(record.refund_id)">编辑</a>
          <a-divider type="vertical" />
          <a @click="toDetail(record.refund_id)">查看</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="是否删除"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDel(record.contract_id, record.refund_id)"
          >
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <a-modal
      centered
      v-model="addVisible"
      title="添加退款信息"
      @ok="addPayment"
      @cancel="resetForm"
    >
      <a-form-model
        ref="form"
        :rules="ruleForm"
        :model="form"
      >
        <a-form-model-item class="form-item" label="退款金额" prop="amount">
          <a-input-number style="width: 100%;" v-model="form.amount" type="text" />
        </a-form-model-item>
        <a-form-model-item label="退款理由" prop="reason">
          <a-textarea v-model="form.reason"></a-textarea>
        </a-form-model-item>
        <a-form-model-item class="form-item" label="退款申请单" prop="apply_file_url">
          <a-upload
            name="file"
            :action="upload"
            :headers="headers"
            :default-file-list="fileList1"
            @change="handleApplyFile"
          >
            <a-button> <a-icon type="upload" /> 上传退款申请单 </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item class="form-item" label="客户沟通截图" prop="communicate_img">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="upload"
            :headers="headers"
            @change="handleChange"
          >
            <img v-if="form.communicate_img" :src="form.communicate_img" width="100" height="100" />
            <div v-else>
              <div class="ant-upload-text">
                上传证明
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="退款备注" prop="remarks">
          <a-textarea v-model="form.remarks"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      centered
      v-model="editVisible"
      title="编辑退款信息"
      @ok="editPayment"
      @cancel="resetForm"
    >
      <a-form-model
        ref="form"
        :rules="ruleForm"
        :model="form"
      >
        <a-form-model-item class="form-item" label="退款金额" prop="amount">
          <a-input-number style="width: 100%;" v-model="form.amount" type="text" />
        </a-form-model-item>
        <a-form-model-item label="退款理由" prop="reason">
          <a-textarea v-model="form.reason"></a-textarea>
        </a-form-model-item>
        <a-form-model-item class="form-item" label="退款申请单" prop="apply_file_url">
          <a-upload
            name="file"
            :action="upload"
            :headers="headers"
            :default-file-list="fileList1"
            @change="handleApplyFile"
          >
            <a-button> <a-icon type="upload" /> 上传退款申请单 </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item class="form-item" label="客户沟通截图" prop="communicate_img">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="upload"
            :headers="headers"
            @change="handleChange"
          >
            <img v-if="form.communicate_img" :src="form.communicate_img" width="100" height="100" />
            <div v-else>
              <div class="ant-upload-text">
                上传证明
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="退款备注" prop="remarks">
          <a-textarea v-model="form.remarks"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import storage from 'store'
import { STable } from '@/components'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import apis from '@/api'
import { refundList2, getAddRefund, postAddRefund, getEditRefund } from '@/api/contract'
import contractColumns from '@/columns/contract'
const refundColumns = contractColumns.refund2
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  props: {
    query: {
      type: Object,
      defalut: () => {}
    }
  },
  components: {
    STable
  },
  name: 'Refund',
  data () {
    return {
      refundColumns,
      refundData: [],
      accountOptions: [],
      queryParam: this.query,
      addVisible: false,
      editVisible: false,
      refundId: 0,
      form: {
        amount: '',
        reason: '',
        apply_file_url: '',
        apply_file_name: '',
        communicate_img: '',
        remarks: ''
      },
      ruleForm: {
        amount: [
          { required: true, message: '必须填写退款金额', trigger: 'blur' }
        ],
        apply_file_url: [
          { required: true, message: '必须上传退款申请单', trigger: 'change' }
        ],
        communicate_img: [
          { required: true, message: '必须上传与客户沟通的截图', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '必须填写退款理由', trigger: 'blur' }
        ]
      },
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      upload: apis.Upload,
      fileList2: [],
      fileList1: []
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      const app = this
      const query = {}
      query['filter[contract_id]'] = this.queryParam['contract_id']
      refundList2(query).then(res => {
        if (res.status === 0) {
          app.refundData = res.result['data']
          app.accountOptions = res.result['status_opts']
        }
      })
    },
    addModal () {
      const app = this
      getAddRefund(app.queryParam['contract_id']).then(res => {
        if (res.status === 0) {
          app.addVisible = true
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    editModal (rid) {
      const app = this
      const fileList1 = []
      const form = {}
      const obj = {}
      app.refundId = rid
      getEditRefund(app.queryParam['contract_id'], rid).then(res => {
        for (const k in res.result.refund) {
          if (k !== 'apply_file_url') {
            form[k] = res.result.refund[k]
          }
        }
        obj['uid'] = '1'
        obj['name'] = res.result.refund.apply_file_name
        obj['status'] = 'done'
        obj['url'] = res.result.refund.apply_file_url
        fileList1.push(obj)
        app.form = form
        app.fileList1 = fileList1
        app.editVisible = true
        app.$emit('addRefund')
      })
    },
    addPayment () {
      const app = this
      const form = {}
      app.$refs.form.validate(valid => {
        if (valid) {
          for (const k in app.form) {
            form['refund[' + k + ']'] = app.form[k]
          }
          form.contract_id = app.queryParam['contract_id']
          postAddRefund(form).then(res => {
            if (res.status === 0) {
              app.addVisible = false
              app.init()
              app.$emit('addRefund')
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
      })
    },
    toDetail (id) {
      this.$router.push({ name: 'RefundDetail', params: { rid: id } })
    },
    editPayment () {
      const app = this
      const form = {}
      for (const k in app.form) {
        form['refund[' + k + ']'] = app.form[k]
      }
      form.contract_id = app.queryParam['contract_id']
      form.refund_id = app.refund_id
      // postEditPay(form).then(res => {
      //   if (res.status === 0) {
      //     app.editVisible = false
      //     app.init()
      //   } else {
      //     app.$warning({
      //       title: res.msg
      //     })
      //   }
      // })
    },
    handleApplyFile (info) {
      console.log(info)
      if (info.file.status === 'done') {
        this.form['apply_file_url'] = info.file.response.result.url
        this.form['apply_file_name'] = info.file.name
      }
    },
    handleChange (info) {
      if (info.file.status === 'done') {
        this.form['communicate_img'] = info.file.response.result.url
      }
    },
    onDel (id) {
      const app = this
      app.queryParam['payment_id'] = id
      // delPayment(app.queryParam).then(res => {
      //   if (res.status === 0) {
      //     app.init()
      //   } else {
      //     app.$warning({
      //       title: res.msg
      //     })
      //   }
      // })
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    downFile (value, filename) {
      window.open(apis.Download + '?value=' + value + '&filename=' + filename)
    },
    onChange (date, dateString) {
      this.form['payment_time'] = dateString
    },
    resetForm () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped>
.form-item {
  margin-bottom: 5px !important;
}
</style>
